package com.zhouheng.springbootactiviti.module.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.zhouheng.common.base.web.Result;
import com.zhouheng.springbootactiviti.common.constants.MenuConstants;
import com.zhouheng.springbootactiviti.common.constants.SecurityConstants;
import com.zhouheng.springbootactiviti.common.pojo.SysUser;
import com.zhouheng.springbootactiviti.module.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.List;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/sys/user")
public class SysUserController {

    @Autowired
    private DefaultKaptcha captchaProducer;

    @Autowired
    private SysUserService sysUserService;

    @ApiOperation("验证码")
    @GetMapping("captcha")
    public void captcha(HttpServletResponse httpServletResponse, HttpSession session) throws Exception {
        byte[] captchaChallengeAsJpeg;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = captchaProducer.createText();
            session.setAttribute(SecurityConstants.SESSION_CAPTCHA, createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = captchaProducer.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(captchaChallengeAsJpeg);
        outputStream.flush();
        outputStream.close();
    }

    @Secured({MenuConstants.USER_MANAGEMENT})
    @ApiOperation("用户列表")
    @GetMapping("list")
    public Result<List<SysUser>> list() {
        return Result.success(sysUserService.list());
    }
}
